<?php
	$goto = isset($_SESSION['return_path']) ? $_SESSION['return_path'] : $path.$table;

	if ($table == 'training_bookings') {
		if (isset($_POST['trainingid'], $_POST['delegates'], $_POST['additional'], $_POST['date'])) {
			$trainingid = $_POST['trainingid'];
			$delegates = $_POST['delegates'];
			$additional = $_POST['additional'];
			$date = $_POST['date'];
			$now = date("Y-m-d H:i:s");
			
			// check no booking exists
			$res = $cn->Data('select id from training_bookings where date='.$date, false);
			if (sizeof($res) > 0) {
				
				echo '<h3>A booking already exists for this date</h3>';
				echo '<p>Most likely this booking was just made, please go <a href="'.$goto.'/add">back</a> and try a new date.</p>';
				unset($trainingid, $delegates, $additional, $date);

			} else {

				// get amount
				$res = $cn->Data('select label, price from training where id='.$trainingid, false);
				$label = $res[0]['label'];
				$price = $delegates * $res[0]['price'];

				// get next id for invoice number
				$inv = $cn->Data('select id from invoices order by id desc limit 1', false);
				if (sizeof($inv) == 0) $nextid = 1;
				else $nextid = intval($inv[0]['id']) + 1;
				$invno = 'SUB'.date('Ym').str_pad($nextid, 4, '0', STR_PAD_LEFT);
				unset($inv);

				// add booking, unpaid
				$res = $cn->Add('training_bookings', array('trainingid'=>$trainingid, 'userid'=>$user_id, 'date'=>$date, 'delegates'=>$delegates, 'additional'=>$additional, 'paid'=>0, 'invoice'=>$invno), false);

				// create invoice, get invoice number add as reference.
				$res = $cn->Add('invoices', array('date'=>$now, 'userid'=>$user_id, 'label'=>$invno, 'amount'=>$price, 'content'=>'New training booking [pending]', 'paid'=>0, 'completed'=>0), false);

				// create a log of transaction
				$res = $cn->Add('logs', array('date'=>$now, 'userid'=>$user_id, 'description'=>'New booking pending. Invoice ['.$invno.']', 'type'=>'training'), false);

				// create form
				$user_email = $userdata['email'];
				$return_url = 'http://'.$server.$path.$table.'/confirm';
				$price = $price * 100;
				$secretKey = md5("10011013800|$invno|$price|ZAR|$return_url|$now|$user_email|secret");//PAYGATE_ID|REFERENCE|AMOUNT|CURRENCY|RETURN_URL|TRANSACTION_DATE|EMAIL|KEY

				$str = '<h2>Confirm Booking Purchase</h2>
					<h3>Amount due: R'.($price/100).'.00</h3>
					<ul class="details grey">
						<li>Training Session</li><li>'.$label.'</li>
						<li>Date</li><li>'.$date.'</li>
						<li>Delegates</li><li>'.$delegates.'</li>
						<li>Dietry Requirements</li><li>'.$additional.'</li>
					</ul>
					<p>You are about to be redirect to a secure <a href="http://www.paygate.co.za" target="_blank">PayGate</a> page to complete this transaction.<br/>On completition of the transaction, using your prefered payment method, you will be returned to your dashboard.</p>
					<p>Please note: The Sett does not store any payment details. All transactions are handled using <a href="http://www.paygate.co.za" target="_blank">PayGate</a>.</p>
				<form action="https://www.paygate.co.za/paywebv2/process.trans" method="POST">
				<input type="hidden" name="PAYGATE_ID" value="10011013800">
				<input type="hidden" name="REFERENCE" value="'.$invno.'">
				<input type="hidden" name="AMOUNT" value="'.$price.'">
				<input type="hidden" name="CURRENCY" value="ZAR">
				<input type="hidden" name="RETURN_URL" value="'.$return_url.'">
				<input type="hidden" name="TRANSACTION_DATE" value="'.$now.'">
				<input type="hidden" name="EMAIL" value="'.$user_email.'">
				<input type="hidden" name="CHECKSUM" value="'.$secretKey.'">
				<input type="submit" value="Proceed" class="button" id="PayGateSubmit">
				</form>';
				echo $str;
			}

			//$now = date("Y-m-d H:i:s");
			//$res = $cn->Data('select startdate, enddate, subscriptiontypeid from subscriptions where userid='.$user_id, false);
			
			//if (sizeof($res) > 0) {
		}
	} else if ($table == 'bookings') {

		if (isset($_POST['userid'], $_POST['spaceid'], $_POST['occupants'], $_POST['date'], $_POST['timeblock'])) {
			$arr = explode(',', $_POST['timeblock']);
			unset($_POST['timeblock']);
			$spaceid = $_POST['spaceid'];
			$time = '';
			$mins = 0;
			for ($i=0; $i<sizeof($arr); $i++) {
				if ($arr[$i] == 1) {
					if ($time == '') $time = date('H:i:s', strtotime($starttime.' + '.($i*30).' minutes'));
					$mins += 30;
				}
			}
			$starttime = $_POST['date'].' '.$time;
			$endtime = date('Y-m-d H:i:s', strtotime($starttime.' + '.$mins.' minutes'));
			
			// let's double check if there is already a booking:
			$newStart = $starttime;
			$newEnd = $endtime;
			$query = "SELECT * FROM bookings WHERE start BETWEEN $newStart AND $newEnd OR end BETWEEN $newStart AND $newEnd OR $newStart BETWEEN start AND end AND spaceid=".$_POST['spaceid'];
			$res = $cn->Data($query, false);
			if (sizeof($res) > 0) {
				
				echo '<h3>A booking already exists for this date / time</h3>';
				echo '<p>Most likely this booking was just made, please go <a href="'.$goto.'/add">back</a> and try a new date.</p>';
				unset($trainingid, $delegates, $additional, $date);

			} else
				//$result = $cn->Add($table, $_POST, false, array('add-submit'));

				// get amount
				$res = $cn->Data('select label, hourlyrate from spaces where id='.$spaceid, false);
				$label = $res[0]['label'];
				$price = $delegates * $res[0]['price'];

				// get next id for invoice number
				$inv = $cn->Data('select id from invoices order by id desc limit 1', false);
				if (sizeof($inv) == 0) $nextid = 1;
				else $nextid = intval($inv[0]['id']) + 1;
				$invno = 'SUB'.date('Ym').str_pad($nextid, 4, '0', STR_PAD_LEFT);
				unset($inv);
		}

	} else {
		header('location: '.$goto);
	}

?>